package com.zl.cms.service;

import com.zl.basic.model.Pager;
import com.zl.basic.model.SystemContext;
import com.zl.cms.dao.IAttachmentDao;
import com.zl.cms.model.Attachment;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.io.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.inject.Inject;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-3-16 Time: 下午6:11
 */
@Service("attachmentService")
public class AttachmentService implements IAttachmentService {
  public static final int IMG_WIDTH = 900;
  public static final int THUMBNAIL_WIDTH = 100;
  public static final int THUMBNAIL_HEIGHT = 80;
  private IAttachmentDao attachmentDao;

  private final static String UPLOAD_PATH = "/upload/";

  public IAttachmentDao getAttachmentDao() {
    return attachmentDao;
  }

	@Override
	public void updateIndexPic(int aid) {
		Attachment att = attachmentDao.load(aid);
		if(att.getIndexPic() ==0) {
			att.setIndexPic(1);
		}else{
			att.setIndexPic(0);
		}
		attachmentDao.update(att);
	}

	@Override
	public void updateAttachInfo(int aid) {
		Attachment att = attachmentDao.load(aid);
		if(att.getAttch() ==0) {
			att.setAttch(1);
		}else{
			att.setAttch(0);
		}
		attachmentDao.update(att);
	}

	@Inject
  public void setAttachmentDao(IAttachmentDao attachmentDao) {
    this.attachmentDao = attachmentDao;
  }

  @Override
  public void add(Attachment a, InputStream is) {
    attachmentDao.add(a);
    saveFile(a, is);
  }

  private void saveFile(Attachment a, InputStream is) {
    try {
      String realPath = SystemContext.getRealPath();
      // + a.getNewName()
      String path =
          realPath + File.separator + "resources" + File.separator + "upload" + File.separator;
      String thumPath =
          realPath + File.separator + "resources" + File.separator + "upload" + File.separator
              + "thumbnail" + File.separator;
      File fp = new File(path);
      File tfp = new File(thumPath);
      System.out.println(fp);
      System.out.println(tfp);
      if (!fp.exists()) {
        fp.mkdirs();
      }
      if (!tfp.exists()) {
        tfp.mkdirs();
      }
      path = path + a.getNewName();
      thumPath = thumPath + a.getNewName();
      if (a.getImg() == 1) {

        BufferedImage oldbi = ImageIO.read(is);
        int width = oldbi.getWidth();
        Builder<BufferedImage> bf = Thumbnails.of(oldbi);
        if (width > IMG_WIDTH) {
          bf.scale((double) IMG_WIDTH / (double) width);
        } else {
          bf.scale(1.0f);
        }
        bf.toFile(path);
        // 缩略图处理
        // 1.将原图压缩
        BufferedImage tbi =
            Thumbnails.of(oldbi).scale(THUMBNAIL_WIDTH * 1.2 / width).asBufferedImage();
        // 2 切割并且保存
        Thumbnails.of(tbi).scale(1.0f)
            .sourceRegion(Positions.CENTER, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT).toFile(thumPath);
      } else {
        FileUtils.copyInputStreamToFile(is, new File(path));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void deleteAttachmentFiles(Attachment a) {
    String realPath = SystemContext.getRealPath();
    realPath += UPLOAD_PATH;
    new File(realPath + a.getNewName()).delete();
  }

  @Override
  public void delete(int id) {
    Attachment attachment = attachmentDao.load(id);
    attachmentDao.delete(id);
    deleteAttachmentFiles(attachment);
  }

  @Override
  public Attachment load(int id) {
    return attachmentDao.load(id);
  }

  @Override
  public Pager<Attachment> findNoUseAttachment() {
    return attachmentDao.findNoUseAttachment();
  }

  @Override
  public void clearNoUseAttachment() {
    attachmentDao.clearNoUseAttachment();
  }

  @Override
  public List<Attachment> listByTopic(Integer tid) {
    return attachmentDao.listByTopic(tid);
  }

  @Override
  public List<Attachment> listIndexPic(Integer num) {
    return attachmentDao.listIndexPic(num);
  }

  @Override
  public Pager<Attachment> findChannelPic(Integer cid) {
    return attachmentDao.findChannelPic(cid);
  }

  @Override
  public List<Attachment> listAttachByTopic(Integer tid) {
    return attachmentDao.listAttachByTopic(tid);
  }
}
